<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <script>
            /*
            思路：这也是构造二叉树，类似于前中构造二叉树，一样需要对数组进行裁剪处理。只不过每次找出数组的最大值
            通过最大值创建节点root，然后最大值左右就是左右子树，然后root.left=buildTree()  root.right=buildTree()
            */
            var constructMaximumBinaryTree = function (nums) {
                function buildTree(nums, left, right) {
                    //注意 终止条件必须是return null undefined貌似会报错
                    if (left > right) return null
                    let maxValue = -1
                    let maxIndex = -1
                    //基于left和right找出数组中的最大值
                    for (let i = left; i <= right; i++) {
                        if (nums[i] > maxValue) {
                            maxValue = nums[i]
                            maxIndex = i
                        }
                    }
                    let root = new TreeNode(maxValue)
                    root.left = buildTree(nums, left, maxIndex - 1)
                    root.right = buildTree(nums, maxIndex + 1, right)
                    return root
                }
                return buildTree(nums, 0, nums.length - 1)
            }
        </script>
    </body>
</html>
